<template>
  <div class="app-container" v-loading="appLoading">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-row class="form-item-group">
        <el-col>

     <el-form-item label="店铺:">
            <el-select v-model="queryParams.storeId" placeholder="请选择店铺编号" filterable clearable size="mini">
              <el-option v-for="option in options.storeOptions" :key="option.storeCode" :label="option.storeName" :value="option.storeCode" />
            </el-select>
    </el-form-item>
     <el-form-item label="子订单号:">
       <el-input v-model="queryParams.sourceItemId" size="mini" placeholder="请输入订单号" width="1" clearable @keyup.enter.native="handleQuery" />
     </el-form-item>
     <el-form-item label="商城SPU:">
       <el-input v-model="queryParams.custSpuId" size="mini" placeholder="请输入商城SPU" width="1" clearable @keyup.enter.native="handleQuery" />
     </el-form-item>
     <el-form-item label="商城SKU:">
       <el-input v-model="queryParams.custSkuId" size="mini" placeholder="请输入商城SKU" width="1" clearable @keyup.enter.native="handleQuery" />
     </el-form-item>
     <el-form-item label="查询年月:">
       <el-select v-model="queryParams.monthYear" filterable clearable>
         <el-option v-for="item in options.jobMonthList" :key="item.key" :label="item.label" :value="item.key" />
       </el-select>
     </el-form-item>
          <el-form-item >
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button v-loading="exportLoading" v-hasPermission="['accounting:accApSkuMonthlySettlement:search']" type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
         </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="40" class="mb5">
      <el-col :span="1.5">
       <span style="padding-left: 2px"><el-tag type="info">销售件数合计：{{ wtCntSum }}</el-tag></span>
   <span style="padding-left: 2px"><el-tag type="info">退单件数合计：{{ returnCntSum }}</el-tag></span>
   <span style="padding-left: 2px"><el-tag type="info">卖出金额合计：{{ contractAmountSum }}</el-tag></span>
   <span style="padding-left: 2px"><el-tag type="info">卖出退单价合计：{{ sumSellRtAmt }}</el-tag></span>
   <span style="padding-left: 2px"><el-tag type="info">买入金额合计：{{ amountSum }}</el-tag></span>
    <span style="padding-left: 2px"><el-tag type="info">买入退单合计：{{ returnAmountSum }}</el-tag></span>
 <span style="padding-left: 2px"><el-tag type="info">销售里程：{{ custMilePaymentAmt }}</el-tag></span>

      </el-col>
    </el-row>

    <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="page.records" highlight-current-row @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
     <el-table-column label="SPU" width="100" align="center"  prop="custSpuId" />
      <el-table-column label="SKU"   width="105" align="center" prop="custSkuId" >
      <template slot-scope="scope">
        <el-button type="text" @click="handleSkuView(scope.row)">{{ scope.row.custSkuId }}</el-button>
      </template>
       </el-table-column>
      <el-table-column label="商品名称"  width="405" show-overflow-tooltip align="center" prop="cargoObjectName" />
 <!-- <el-table-column label="子订单号" width="185"  align="center" prop="sourceItemId"  />
 -->
      <el-table-column label="销售数" width="89" align="center" prop="originalSellQty" />
      <el-table-column label="销售金额" align="center" width="112"  prop="salesOriginAmount">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.salesOriginAmount).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退单件数" align="center" width="99"  prop="returnQty" />

      <el-table-column label="退单金额" align="center" width="99"  prop="buyReturnAmt">
        <template slot-scope="scope">
            <span>{{ Number(scope.row.buyReturnAmt).toFixed(2) }}</span>
          </template>
        </el-table-column>
      <!--  <el-table-column label="退单日期" align="center" prop="returnTime" width="120">
           <template slot-scope="scope">
            <span>{{ parseTime(scope.row.returnTime) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="订单月份" width="89" align="center" prop="monthYear" />
        <el-table-column label="销售单价" align="center" width="122"  prop="amtGenAr">
          <template slot-scope="scope">
            <span>{{ Number(scope.row.amtGenAr).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="买入单价" align="center" width="122"  prop="rate">
          <template slot-scope="scope">
            <span>{{ Number(scope.row.rate).toFixed(2) }}</span>
          </template>
        </el-table-column>
   <!--     <el-table-column label="折扣编码" width="185"  align="center" prop="discountActivityCode"  />
 -->
     <el-table-column label="买入价" align="center" width="112"  prop="contractRate">
       <template slot-scope="scope">
         <span>{{ Number(scope.row.contractRate).toFixed(2) }}</span>
       </template>
     </el-table-column>







         <el-table-column label="店铺" align="center" show-overflow-tooltip width="180">
              <template slot-scope="scope">
                <el-button type="text" @click="handleView(scope.row)">{{ scope.row.storeName }}</el-button>
              </template>
      </el-table-column>
  <!--    <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
       <template slot-scope="scope">
          <el-button type="text" v-if="handleReturnBtnShow(scope.row.status)" size="mini" @click="handleEditPrice(scope.row)">编辑结算</el-button>
        </template>
    </el-table-column> -->
    </el-table>
    <!-- 分页 -->

    <!-- 添加/修改对话框 -->



  </div>
</template>

<script>
import AccountingApApi from '@/api/accounting/AccountingApApi'
import CustomerApi from '@/api/basic/CustomerApi'
import StoreApi from '@/api/basic/StoreApi'
import SalesOrderItemApi from '@/api/order/SalesOrderItemApi'
import SupplierApi from '@/api/basic/SupplierApi'
const defaultAccountingApFormData = {
  invoiceNo: null,
  slipNo: null,
  storeId: null,
  mallId: null,
  status: '0',
  fixStatus: '0',
  basicNo: null,
  orderSeqNo: null,
  orderItemNo: null,
  acItemId: null,
  site: null,
  bizKind: null,
  bizUnit: null,
  accUnit: null,
  branchUnit: null,
  payCust: null,
  billToCust: null,
  ptnrYn: null,
  slipDt: null,
  invoiceType: null,
  taxType: null,
  amtCur: null,
  jobDate: null,
  exrate: null,
  curr: null,
  rate: null,
  wtCnt: null,
  frtCd: null,
  frtNm: null,
  invoiceDt: null,
  miles: null,
  invSettleId: null,
  settlementId: null,
  billNo: null,
  carrierNo: null,
  dispatchId: null,
  distributionNo: null,
  inputType: null,
  autoYn: null,
  pcTerm: null,
  cargoObjectNo: null,
  cargoObjectName: null,
  vehicleNo: null,
  apTypeFlag: null,
  carrierEdiYn: null,
  amount: null,
  paiedFee: null,
  consigneeName: null,
  amtAr: null,
  cargoDamageYn: null,
  remainedAmount: null,
  originalCustName: null,
  batchWorkorderNo: null,
  shippedQtyUnit: null,
  shipperName: null,
  contractAmount: null,
  contractRate: null,
  driverNo: null,
  paymentType: null,
  settlementApplicant: null,
  returnTime: null,
  sourceItemId: null,
  askedTransitFee: null,
  settleBasedOn: null,
  settleBasedOnUnit: null,
  dispatchDate: null
}
export default {
  name: 'AccountingApList',
  data() {
    return {
      options: {
        mallOptions: [],
        supplierIdOptions: [], // 供应商编号字典
        storeOptions: [],
        jobMonthList: this.$constant.jobMonthOptions,
        sysYnTypeOptions: this.$constant.sysYnTypeOptions
      },
      queryParams: {
        storeId: null,
        monthYear: null,
        sortProperty: null,
        sortDirection: null,
        custSpuId: null,
        sourceItemId: null,
        custSkuId: null
      },
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      editPriceDialog: {
        title: '编辑价格',
        visible: false
      },
      editPriceDialogData: {
        amount: null,
        contractAmount: null,
        amtGenAr: null,
        rate: null,
        id: null
      },
      returnDialog: {
        title: '退单',
        visible: false
      },
      returnDialogData: {
        returnQty: null,
        id: null
      },
      accountingApFormDialog: {
        title: '',
        visible: false
      },
      accountingApFormData: Object.assign({}, defaultAccountingApFormData),
      accountingApFormRules: {
        invoiceNo: [{ required: true, message: '发票号不能为空', trigger: 'blur' }],
        slipNo: [{ required: true, message: '支付流水号不能为空', trigger: 'blur' }]
      },
      loading: true,
      appLoading: false,
      exportLoading: false,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true,
      amountSum: null,
      contractAmountSum: null,
      returnAmountSum: null,
      sumSellRtAmt: null,
      returnCntSum: null,
      custMilePaymentAmt: null,
      wtCntSum: null
    }
  },
  created() {
   // this.initParam()
   // this.handleQuery()
     this.loading = false
    this.loadOptions()
  },
  methods: {
    initParam() {
     this.queryParams.monthYear =null
     // this.queryParams.monthYear = this.parseTime(new Date(), '{y}-{m}')
    },
    loadOptions() {
      let  that = this;
      CustomerApi.list().then(response => {
        that.options.mallOptions = response.data
      })
      StoreApi.list().then(response => {
        that.options.storeOptions = response.data
      })
      SupplierApi.list().then(response => {
        that.options.supplierIdOptions = response.data
      })
    },
    handleAdd() {
      this.openAccountingApFormDialog()
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return AccountingApApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openAccountingApFormDialog(id)
    },
    handleQuery() {
      if(!this.queryParams.monthYear){
       this.$message.warning("请选择结算月度")
        return false;
      }
      this.loading = true
      this.returnAmountSum=0.0
       this.returnCntSum =0.0
       this.sumSellRtAmt =0.0
       this.custMilePaymentAmt =0.0
       this.amountSum =0.0
       this.contractAmountSum = 0.0
       this.wtCntSum =0.0
      //AccountingApApi.settlementViewMonthly(this.queryParams, this.page).then(response => {
      AccountingApApi.settlementViewSkuMonthly(this.queryParams, this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
      // 查询汇总信息
      AccountingApApi.settlementViewMonthlySum(this.queryParams).then(response => {
        this.amountSum = response.data.amountSum
        this.contractAmountSum = response.data.contractAmountSum
        this.wtCntSum = response.data.wtCntSum
        this.custMilePaymentAmt= response.data.custMilePaymentAmt
      })
      AccountingApApi.settlementViewMonthlyReturnSum(this.queryParams).then(response => {

          this.returnAmountSum= response.data.sumRtAmt
          this.sumSellRtAmt= response.data.sumSellRtAmt
         this.returnCntSum = response.data.sumRtQty


      })
    },

    handleSkuView(row) {
      // this.$router.push({ path: '/accountingAp/viewSkuOrder/' + row.custSkuId+'/'+this.queryParams.monthYear })
      window.open(window.location.origin + '/#/accountingAp/viewSkuOrder/' + row.custSkuId+'/'+this.queryParams.monthYear)
    },
    handleView(row) {
      this.$router.push({ path: '/store/form/' + row.storeId })
    },
    // handleOrderView(row) {
    //   this.$router.push({ path: '/order/salesOrder/form/' + row.storeId })
    // },

    handleExport() {
      // if (!this.queryParams.storeId) {
      //   this.$message.warning('导出操作店铺不能为空')
      //   return false
      // }
      let that = this
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        that.exportLoading = true
        return AccountingApApi.exportreportData(that.queryParams)
      }).then(response => {
        that.exportLoading = false
        this.$common.download(response.data)
      }).catch(() => {
        that.exportLoading = false
      })
    },
    openAccountingApFormDialog(id) {
      this.accountingApFormDialog.visible = true
      if (id) {
        this.accountingApFormDialog.title = '财务应付-修改'
        AccountingApApi.get(id).then(response => {
          this.accountingApFormData = {
            ...this.accountingApFormData,
            ...response.data
          }
        })
      } else {
        this.accountingApFormDialog.title = '财务应付-添加'
      }
    },
    handleSortChange(sort) {
      if (sort.order) {
        this.queryParams.sortProperty = sort.prop
        this.queryParams.sortDirection = sort.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.queryParams.sortProperty = null
        this.queryParams.sortDirection = null
      }
      this.handleQuery()
    },
    confirmAccountingApFormDialog() {
      this.$refs['accountingApForm'].validate(valid => {
        if (valid) {
          if (this.accountingApFormData.id) {
            AccountingApApi.edit(this.accountingApFormData).then(response => {
              this.$message.success('修改成功')
              this.resetAccountingApFormDialog()
              this.handleQuery()
            })
          } else {
            AccountingApApi.add(this.accountingApFormData).then(response => {
              this.$message.success('添加成功')
              this.resetAccountingApFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetAccountingApFormDialog() {
      this.accountingApFormDialog = {
        title: '',
        visible: false
      }
      this.accountingApFormData = Object.assign({}, defaultAccountingApFormData)
      this.resetForm('accountingApForm')
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },

    handleFix(row) {
      this.appLoading = true
      AccountingApApi.fixData().then(() => {
        this.appLoading = false
        this.$message.success('修复成功!')
        this.handleQuery()
      }).catch(error => {

        console.log(error)
        this.$message.error('修复失败!')
        this.appLoading = false
      })
    },
    handleFixTwo(row) {
      this.appLoading = true
      AccountingApApi.fixDataTwo().then(() => {
        this.appLoading = false
        this.$message.success('修复成功!')
        this.handleQuery()
      }).catch(error => {
        console.log(error)
        this.$message.error('修复失败!')
        this.appLoading = false
      })
    },

    handleEditPrice(row) {
      this.editPriceDialog.visible = true
      this.editPriceDialogData.amount = row.amount
      this.editPriceDialogData.rate = row.rate
      this.editPriceDialogData.amtGenAr = row.amtGenAr
      this.editPriceDialogData.contractAmount = row.contractAmount
      this.editPriceDialogData.id = row.id
    },
    closeEditPriceDialog() {
      this.editPriceDialog = {
        title: '编辑价格',
        visible: false
      }
      this.editPriceDialogData = {
        amount: null,
        rate: null,
        amtGenAr: null,
        contractAmount: null,
        id: null
      }
      this.handleQuery()
    },
    confirmEditPriceDialog() {
      const params = {
        amount: this.editPriceDialogData.amount,
        rate: this.editPriceDialogData.rate,
        amtGenAr: this.editPriceDialogData.amtGenAr,
        contractAmount: this.editPriceDialogData.contractAmount,
        amount: this.editPriceDialogData.amount,
        id: this.editPriceDialogData.id
      }
      AccountingApApi.editPrice(params).then(() => {
        this.$message.success('编辑成功!')
        this.closeEditPriceDialog()
      })
      this.handleQuery()
    },
    handleReturn(row) {
      this.returnDialog.visible = true
      this.returnDialogData.returnQty = row.wtCnt
      this.returnDialogData.id = row.sourceItemId
    },
    closeReturnDialog() {
      this.returnDialog = {
        title: '退单',
        visible: false
      }
      this.returnDialogData = {
        returnQty: null
      }
      this.handleQuery()
    },
    confirmReturnDialog() {
      const params = {
        returnQty: this.returnDialogData.returnQty,
        id: this.returnDialogData.id
      }
      SalesOrderItemApi.createReturn(params).then(() => {
        this.$message.success('退单成功!')
        this.closeReturnDialog()
      })
      this.handleQuery()
    },
    handleReturnBtnShow: function(status) {
      const validStatusList = ['CREATED']
      const index = validStatusList.indexOf(status)
      if (index === -1) {
        return false
      } else {
        return true
      }
    },
    resetQuery() {
      this.page.current = 1
      this.queryParams = {
        mallId: null,
        payCust: null,
        storeId: null,
        basicNo: null,
        isValid: this.$constant.Y
      }
      this.handleQuery()
    }
  }
}
</script>
